package org.example;

import java.sql.*;

public class JDBCUtil {
    private static String url = "jdbc:mysql://localhost:3306/mydb";
    private static String username = "root";
    private static String password = "asdfghjkl";
    //静态代码块
    static {
        try {
            //加载驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    //定义静态方法，创建对象并返回
    public static Connection getCon() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    //关闭连接
    public static void close(ResultSet rs, PreparedStatement ps, Connection con) {
        try {
            if (rs != null) {
                rs.close();
            }
            if ((ps != null)) {
                ps.close();
            }
            if (con != null) {
                con.close();
            }
        }catch (SQLException sql){
            System.out.println("关闭资源异常"+sql.getMessage());
        }

    }
}
